package yyy.ab.modules.security.handler;

import lombok.extern.slf4j.Slf4j;;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理类
 */
@Slf4j
public class AbAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    /**
     * @param defaultFailureUrl 登录失败跳转的地址
     */
    public AbAuthenticationFailureHandler(String defaultFailureUrl) {
        super();
        setDefaultFailureUrl(defaultFailureUrl);
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            String username = request.getParameter("username");

        }
        super.onAuthenticationFailure(request, response, e);
//        //登录失败信息返回
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("code", "500");
//        paramMap.put("message", e.getMessage());
//        //设置返回请求头
//        response.setContentType("application/json;charset=utf-8");
//        //写出流
//        PrintWriter out = response.getWriter();
//        out.write(JSONObject.toJSONString(paramMap));
//        out.flush();
//        out.close();
    }
}
